<?php

namespace api\controllers;

use yii;
use common\models\User;
use api\models\LoginForm;
use Firebase\JWT\JWT;


class IndexController extends CommonController {

    

    /**
     * 
     */
    public function actionLogin() {
        $error = true;
        $message = "";
        $objects = [];
        //
        $email = \Yii::$app->request->post('email','');
        $password = \Yii::$app->request->post('password','');
        $login = new LoginForm();
        $login->email = $email;
        $login->password = $password;
        if($login->validate()){
            $error = false;
            yii::$app->session->set('user', $login->user);
        }else{
            $message = $this->parserMessage($login->getErrors());
        }
        //
        $result = ['error' => $error,'message' => $message,'objects' => $objects];
        $this->setHeader(200);
        echo json_encode($result);
        exit();
    }
    
    /**
     * 
     */
    public function actionInfo(){
        $error = true;
        $message = "";
        $objects = [];
        //
        if(yii::$app->session->has('user')){
            $error = false;
            $user = yii::$app->session->get('user');
            $id_category = $user->findRootCategory();
            $brands = $user->findBrandForLogin();
            $info = [
                'id_user' => $user->id_user,
                'name' => $user->name,
                'id_company' => $user->id_company,
                'id_category' => $id_category,
                'id_branch' => $brands['main'],
                'brands' => $brands['brands'],
                'exp' => strtotime("+ 24 hours")
            ];
            $objects = [
                'id_user' => $user->id_user,
                'name' => $user->name,
                'id_company' => $user->id_company,
                'id_category' => $id_category,
                'id_branch' => $brands['main'],
                'brands' => $brands['brands'],
                'token' => JWT::encode($info, $this->key)
            ];
        }
        //
        $result = ['error' => $error,'message' => $message,'objects' => $objects];
        $this->setHeader(200);
        echo json_encode($result);
        exit();
    }

    /**
     * 
     */
    public function actionLogout(){
        $error = false;
        $message = "";
        $objects = [];
        //
        if(yii::$app->session->has('user')){
            yii::$app->session->remove('user');
        }
        //
        $result = ['error' => $error,'message' => $message,'objects' => $objects];
        $this->setHeader(200);
        echo json_encode($result);
        exit();
    }
    
    
    

}
